<?php

class SocialService extends AbstractService
{

    /**
     * @var SocialService
     */
    private static $instance;

    /**
     * Get the instance of SocialService.
     *
     * @return SocialService
     */
    public static function get()
    {
        if (!self::$instance) {
            self::$instance = new SocialService();
        }
        return self::$instance;
    }

    /**
     * Construction.
     */
    protected function __construct()
    {
        parent::__construct();
    }

    /**
     * 处理创建时的逻辑
     *
     * @param int $shardId
     * @return void
     */
    public function handleCreate($shardId)
    {

    }

    /**
     * 处理用户登录时的逻辑
     *
     * @param int $userId
     * @return void
     */
    public function handleLogin($userId)
    {

    }

    /**
     * 处理用户登录时的逻辑
     *
     * @param int $userId
     * @return array()
     */
    public function info($userId)
    {
        return [];
    }

    /**
     *  发送社交消息
     * @param int $userId 用户ID
     * @param int $targetId 被操作者ID
     * @param int $itemDefId 道具ID
     * @param int $count 道具数据
     * @param int $reqTime
     * @return void
     */
    public function sendMessage($userId, $targetId, $itemDefId, $count, $reqTime)
    {
        if ($userId == $targetId) {
            return;
        }
        /**
         * @var Redis $cache
         */
        $cache = SzCacheFactory::get()->getAppCache($targetId);
        $hashKey = GameConst::CACHE_KEY_SOCIAL_MESSAGE_HASH . $targetId;
        $cacheInfo = $cache->hGet($hashKey, $userId);
        if ($cacheInfo && is_array($cacheInfo) && count($cacheInfo) == 2 && $reqTime - $cacheInfo[0] <= GameConst::SOCIAL_MERGE_TIME) {
            $reqTime = $cacheInfo[0];
            if (isset($cacheInfo[1][$itemDefId])) {
                $cacheInfo[1][$itemDefId] += $count;
            } else {
                $cacheInfo[1][$itemDefId] = $count;
            }
        } else {
            $cacheInfo = [$reqTime, [$itemDefId => $count]];
        }
        $cache->hSet($hashKey, $userId, $cacheInfo);

        //消息压入消息队列, 删除多余的消息，因为会有重复消息，故保留的数据为需要的数据的2倍

        $message = [$userId, $reqTime, $cacheInfo[1]];
        $listKey = GameConst::CACHE_KEY_SOCIAL_MESSAGE_LIST . $targetId;
        $cache->lPush($listKey, json_encode($message));
        $cache->lTrim($listKey, 0, GameConst::SOCIAL_MAX_COUNT * 2);//删除多余的消息
    }


    /**
     *  获取社交消息
     * @param int $userId
     * @param int $reqTime
     * @return int
     */
    public function getMessage($userId, $reqTime)
    {
        /**
         * @var Redis $cache
         */
        $cache = SzCacheFactory::get()->getAppCache($userId);
        $listKey = GameConst::CACHE_KEY_SOCIAL_MESSAGE_LIST . $userId;
        $listMessage = $cache->lRange($listKey, 0, -1);

        $count = 0;

        $lastTime = [];
        $messageList = [];
        $lastKey = null;

        $userInfo = [];

        $totalCount = SzConfig::get()->loadAppConfig(ModuleProfileConst::CONFIG_PROFILE, 'umberOfMutualaid', true);

        foreach ($listMessage as $key => $info) {
            $info = json_decode($info, true);
            if (!is_array($info) || count($info) != 3) {
                continue;
            }
            list($target, $targetTime, $items) = $info;
            if ($reqTime - $targetTime > GameConst::SOCIAL_VALID_TIME) {//只保留3天前的
                $lastKey = $key;
                break;
            }
            //同一个用户时间相同则是同一条消息，直接跳过
            if (isset($lastTime[$target]) && $lastTime[$target] == $targetTime) {
                continue;
            } else {
                $lastTime[$target] = $targetTime;
            }
            if (++$count >= GameConst::SOCIAL_MAX_COUNT) {
                $lastKey = $key;
                break;
            }
            $message = [
                'userId' => $target,
                'reqTime' => $targetTime,
                'items' => $items,
            ];
            $messageList[] = $message;
            if (isset($userInfo[$target])) {
                continue;
            }
            $friendCount = FriendService::get()->getFriendHandleInfo($userId, $target, $totalCount);
            if ($friendCount < $totalCount['value']) {
                $status = PlantService::get()->isCanStealFlower($userId, $target);
            } else {
                $status = 0;
            }
            $profileInfoList = SzPersister::get()->getVoList($target, ModuleProfileConst::ORM_NAME_PROFILE_INFO);
            $gender = UserService::get()->getInfo($target, GameConst::USER_INFO_TYPE_GENDER, $profileInfoList);
            $userInfo[$target] = [
                'username' => UserService::get()->getTownName($target, $profileInfoList),
                'level' => UserService::get()->getUserLevel($target),
                'headImg' => UserService::get()->getHeadIcon($target, $profileInfoList),
                'gender' => is_null($gender) ? 0 : $gender,
                'status' => intval($status)
            ];
        }
        if (!is_null($lastKey)) {
            $cache->lTrim(GameConst::CACHE_KEY_SOCIAL_MESSAGE_LIST . $userId, 0, $lastKey);//删除多余的消息
        }
        return ['messageList' => $messageList, 'userInfo' => $userInfo];
    }
}
